$(document).ajaxComplete(function(event, xhr, settings) {
	if (xhr.status == 401) {
		layer.alert('用户登录已过期，请重新登录！', function (index) {
			layer.close(index);
			top.location.href = '/';
		});
	};
	if (xhr.status == 500) {
		console.log(xhr.responseJSON.reason);
		layer.msg('服务器内部出错，请联系管理员！');
	};
	if (xhr.status == 0) {
		layer.msg('后台服务已停！');
	};
});

/*右上角任务列表*/
$(".secondPic").click(function(){
	$(this).addClass("active");
	$(".allCon,.taskList2").addClass("active");
	$(this).find('.badge_projectplan').text('');
	loadOtherData();
});

$(".taskList2 .close2").click(function () {
	$(".taskList2,.secondPic").removeClass("active");
	$(".allCon").removeClass("active");
});

//加载待审批数据图标的状态
function load_audit_status() {
    $.ajax({
        url: '/meetingApplication/queryNoAuditData?' + Math.random(),
        dataType: 'json',
        success: function (e) {
            if (e.length > 0) {
                $('.topPic .secondPic img').attr('src', '/img/no_plan.gif');
            } else {
                $('.topPic .secondPic img').attr('src', '/img/no_plan_no.png');
            }
        }
    });
};

load_audit_status();

//加载审批数据
function loadOtherData() {
	var noApproveList = $('.taskList2').hasClass('active');
	if (!noApproveList) {
		return false;
	}
	//判断是否打开未计划面板或者延期面板
	var target_dom = $(".taskList2 div[name='task_div']");
	//先清空内容
    target_dom.empty();
	//页面加载层
	var index = layer.load(0, {
		shade: [0.3,'#000000'] //0.1透明度的白色背景
	});
	$.ajax({
		url: "/meetingApplication/queryNoAuditData?" + Math.random(),
		dataType: 'json',
		success: function (e) {
			var html = '<ul style="margin-top: 32px;">';
            $.each(e, function (index, data) {
				var applicationDate = data.applicationDate == data.applicationDateSecond ? data.applicationDate.substr(5, 11) : (data.applicationDate.substr(5, 11) + '~' + data.applicationDateSecond.substr(5, 11));
                html += '<li class="clearfix">' +
                    '       <span class="myfl" style="height: 22px;line-height: 22px;">' + data.meetingRoomName + '&nbsp;&nbsp;&nbsp;&nbsp;' + applicationDate + '&nbsp;&nbsp;&nbsp;&nbsp;' + data.startTime + '-' + data.endTime +
					'		</span>' +
					' 		<span class="agree">同意</span>' +
					' 		<span class="disagree">拒绝</span>' +
                    '<input type="hidden" name="id" value="'+data.id+'">'+
                    '       <div class="taskOut2">' +
                    '           <table class="table mytable">' +
                    '               <thead>' +
                    '                   <tr>' +
                    '                       <th>会议主题</th>' +
                    '                       <th>申请人</th>' +
                    '                       <th>申请部门</th>' +
                    '                       <th>会议日期</th>' +
                    '                       <th>会议时间段</th>' +
                    '                       <th>申请时间</th>' +
                    '                       <th>会议室</th>' +
                    '                   </tr>' +
                    '               </thead>' +
                    '               <tbody>' +
                    '                   <tr>' +
                    '                       <td>' + data.meetingTheme + '</td>' +
                    '                       <td>' + data.applicantName + '</td>' +
                    '                       <td>' + data.applicantDepartmentName + '</td>' +
                    '                       <td>' + applicationDate + '</td>' +
                    '                       <td>' + data.startTime + '-' + data.endTime + '</td>' +
                    '                       <td>' + data.createTime + '</td>' +
                    '                       <td style="white-space: normal;min-width: 100px;">' + data.meetingRoomName + '</td>' +
                    '                   </tr>' +
                    '               </tbody>' +
                    '           </table>' +
                    '       </div>' +
                    '   </li>';
            });
            target_dom.append(html);
			//关闭加载层
			layer.close(index);
		}
	});

}


/*右上角显示任务列表滑入功能*/
$(".taskList2").delegate('ul li', 'mouseenter', function () {
	var th = $(this).find("div");
	$(".taskListContent").addClass("active").stop().html($(th).html());
});
$(".taskList2").delegate('ul li', 'mouseleave', function () {
	$(".taskListContent").removeClass("active").html("");
});

//数字四舍五入
function round(data) {
	return Math.round(data * 100) / 100;
}

//百分比计算
function round_percent(data) {
	// return round(data) * 100 + '%';
	return Math.floor(data * 10000) / 100 + '%';
}

//转换null值为空字符串
function convertNullValue(data) {
	if (data == null) {
		return '';
	} else if (data == '0000-00-00') {
		return '';
	} else {
		return data;
	}
}

//格式化时间戳
function date_formate(e) {
	var date = new Date(e);
	Y = date.getFullYear() + '-';
	M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
	D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
	h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
	m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
	s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
	return Y+M+D+h+m+s;
}


/*查看更多事件*/
function seeMore(date){
    var content_url = '/meetingApplication/queryMore/?applicationDate=' + date;
	layer.open({
		type: 2,
		title: '数据列表',
		shadeClose: true,
		shade: 0.8,
		area: ['70%', '80%'],
		content: content_url
	});
};

//画日历结构
function draw_calander(date)
{
	var param_date = moment(date);
	//指定日期的月份
	var month = param_date.month();
	//指定日期的年份
	var year = param_date.year();
	//指定日期的日
	var date1 = param_date.date();
	//指定日期的星期
	var day_of_week = param_date.format('dddd');

	//设置页面参数
	$(".mycal .midData .ym .y").text(year);

	$(".mycal .midData .ym .m").text(('0'+(month + 1)).slice(-2));

	//获取日历要显示的第一天和最后一天
	var start_date = moment(param_date).date(1).day(0);
	var end_date = moment(param_date).endOf('month');
	//调接口，获取数据
	var resultData = [];

    //根据类型拼接请求参数
    var url = "/meetingApplication/queryCalendarMeetingData?" + Math.random();

	//页面加载层
	var index = layer.load(0, {
		shade: [0.3,'#000000'] //0.1透明度的白色背景
	});
	$.ajax({
		url: url,
		data: {'startDate': start_date.format('l'),'endDate': end_date.format('l')},
		async: false,
		dataType: 'json',
		success: function (e) {
			resultData = e;
		}
	});
	//计算日历要显示的天数
	var days = end_date.diff(start_date, 'days') + 1;
	//计算日历显示的行数
	var rows = Math.ceil(days / 7);
	//清空日历结构
	$(".cal").html('');
	//增加天数变量
	var day = 0;
	for (var i = 0; i < rows; i++) {
		while (true) {
			if (day == days) {
				break;
			}
			//结构内填写的日期
			var div_date = moment(start_date).add(day, 'd');
			var day_div = div_date.date();
			var month_div = div_date.month();
			var format = div_date.format('l');
			var calander = '<div class="calcon" date_date="'+ format+'">' +
								'<div class="caldate text-r ">' +
								'	<span style="display: none" class="more myfl" onclick="seeMore(\'' + format + '\')">[更多]</span>' +
								'	<span style="cursor: pointer" class="date' + (month_div == month ? (moment().isSame(div_date, 'day') ? ' active' : '') : ' disabled') + '" onclick="seeMore(\'' + format + '\')">' + day_div + '</span>' +
								'</div>' +
							'</div>';
			$(".cal").append(calander);

			//内容数量累计变量
			var list_count = 0;
			var calllist_dom = '';
			for (var j = 0;j < resultData.length; j++) {
				var list_data = resultData[j];
				if (div_date.isBetween(list_data.applicationDate, list_data.applicationDateSecond, 'day') || div_date.isSame(list_data.applicationDate, 'day') || div_date.isSame(list_data.applicationDateSecond, 'day')) {
					list_count++;
					if (list_count == 5) {
						break;
					}
					var data_status = list_data.status;
					var startTime = list_data.startTime;
					var endTime = list_data.endTime;
					calllist_dom += '<div class="callist clearfix">' +
								'      <input type="hidden" name="id" value="' + list_data.id + '">' +
								'      <span class="wl100 ' + (data_status == 2 ? 'blue' : (data_status == 3 ? 'grey' : 'pink')) + '">' + startTime + ' - ' + endTime + '</span>' +
								'      <span class="name wr100">' +
											list_data.meetingRoomName +
								'		</span>' +
								'    </div>';
				}
			}
			var $calcon = $(".cal .calcon:last-child");
			if (list_count > 0) {
				$calcon.addClass('hasShadow');
				$calcon.append(calllist_dom);
			}
			if (list_count == 5) {
				$calcon.find('.more').show();
			}
			day++;
		}
	};
	//关闭加载层
	layer.close(index);
};

function monthDay(date){
	var json = {
		showDate:[],
		list:[],
	};
	$(".mycal .midData .ym .y").text(date.split("-")[0]);
	$(".mycal .midData .ym .m").text(date.split("-")[1]);

	var dates = [];
	for(var i = 0; i < 35; i++) {
		var startDate = moment(date).date(1);
		dates[i] = startDate.day(i).date();
	};
	console.log(startDate,dates)

	for (var j = 0; j < dates.length; j++) {
		json.showDate[j] = dates[j];
	}
	for (var k = 0; k < dates.length; k++) {
		$(".cal .calcon").eq(k).find(".caldate .date").text(json.showDate[k]);
	}


};

/*月份增减*/
$(".mycal .midData .ymright").click(function(){
	var year = $(".mycal .midData .ym .y").text();
	var month = $(".mycal .midData .ym .m").text() - 1;
	var date = $(".mycal .day .nowdate").text();
	var v = moment([year, month, date]);
	v.add(1, 'months');
	draw_calander(v);
});

$(".mycal .midData .ymleft").click(function(){
	var year = $(".mycal .midData .ym .y").text();
	var month = $(".mycal .midData .ym .m").text() - 1;
	var date = $(".mycal .day .nowdate").text();
	var v = moment([year, month, date]);
	v.subtract(1, 'months');
	draw_calander(v);
});

/*当前月份初始化*/
function init(date){
	$(".mycal .day .nowdate").text(moment(date).get("date"));
	$(".mycal .day .weekday").text(moment(date).format("dddd"));

	$(".mycal .day .nowdate,.mycal .day .weekday").click(function () {
		draw_calander(date);
	})
}


$(".cal").on('click','.calcon .callist',function(){
	var id = $(this).find("input[name='id']").val();
	layer.open({
		type: 2,
		title: '',
		shadeClose: true,
		shade: 0.8,
		area: ['60%', '70%'],
		content: '/meetingApplication/queryDetailInfo?id=' + id
	});
});


$(".showLayer").on('click','ul li > span:first-child',function(){
	debugger;
	var id = $(this).parent().find("input[name='id']").val();
	if (id == undefined || id == '') {
		return;
	}
	layer.open({
		type: 2,
		title: '',
		shadeClose: true,
		shade: 0.8,
		area: ['60%', '70%'],
		content: '/meetingApplication/queryDetailInfo?id=' + id
	});
});


/*右上角审批列表里搜索框下拉结果显示*/
$(".listSer input").on("focus",function () {
    var $this = $(this);
	//判断打开的面板
	var $parent = $(this).parent().parent();
	var winbid_flag = $parent.hasClass('taskList');
	var noplan_flag = $parent.hasClass('taskList1');
	var delay_flag = $parent.hasClass('taskList2');
	var filter_flag = 0;
	if (winbid_flag) {
		filter_flag = 1;
	}
	if (noplan_flag) {
		filter_flag = 2;
	}
	if (delay_flag) {
		filter_flag = 3;
	}
    $(this).parent().find(".search_res").show().html("");
    if($(this).val().length > 0){
        $(this).parent().find(".delSer").show();
        $(this).parent().find(".search_res").append("<div class=\"getRes\">搜索结果查询中...</div>");
        $.ajax({
            url: "/projectPlanView/getSelectKeyNew",
            data: {'selectKey': $(this).val(),'filter_flag': filter_flag},
            dataType: 'json',
            success: function (e) {
                var serlist= "";
                for (var i = 0;i<e.length;i++) {
                    serlist += '<div class="serlist" data_id="' + e[i].id + '" data_type="' + e[i].type + '">' + e[i].name + '</div>'
                }
                $this.parent().find(".search_res").html("").append(serlist)
            },
            error:function (e) {
                $(".listSer").find(".search_res .getRes").html("后台接口异常");
            }
        });
    }else {
        $(this).parent().find(".search_res").append("<div class=\"getRes\">请输入搜索关键字...</div>");
    }

    $(this).bind('input propertychange',function () {
        if($(this).val().length > 0){
            $(this).parent().find(".delSer").show();
            $(this).parent().find(".search_res").html("");
            $(this).parent().find(".search_res").append("<div class=\"getRes\">搜索结果查询中...</div>");
            $.ajax({
                url: "/projectPlanView/getSelectKeyNew",
                data: {'selectKey': $(this).val(),'filter_flag': filter_flag},
                dataType: 'json',
                success: function (e) {
                    var serlist= "";
                    if (e.length > 0){
                        for (var i = 0;i<e.length;i++) {
                            serlist += '<div class="serlist" data_id="' + e[i].id + '" data_type="' + e[i].type + '">' + e[i].name + '</div>'
                        }
                        $(".listSer").find(".search_res .getRes").remove();
                        $(".listSer .search_res").html(serlist);
                    } else {
                        $(".listSer").find(".search_res .getRes").html("无搜索结果");
                    }
                },
                error:function (e) {
                    $(".listSer").find(".search_res .getRes").html("后台接口异常");
                }
            });
        }else {
            $(this).parent().find(".delSer").hide();
            setTimeout(function () {
                $(".listSer .search_res").html("").append("<div class=\"getRes\">请输入搜索关键字...</div>");
            },400)
        }
        return false;
    })
});
$(".listSer").on('mousedown','.serlist',function (e) {
    var thisVal = $(this).text();
    $(this).parent().parent().find("input").val(thisVal);
	$(this).parent().parent().find('button').triggerHandler('click');
});
/*离焦事件*/
$(".listSer input").on("blur",function () {
    $(this).parent().find(".search_res").hide();
    $(this).unbind('input propertychange');
});
/*点击清空搜索图标*/
$(".listSer .delSer").mousedown(function (event) {
    $(this).parent().find("input").val("");
    $(this).hide();
    $(".listSer .search_res").html("");
    $(this).parent().find(".search_res").append("<div class=\"getRes\">请输入搜索关键字...</div>");
	$(this).parent().find('button').triggerHandler('click');
    event.preventDefault();
});

/*申请会议室*/
$("#apply").click(function () {
	layer.open({
		type: 2,
		title: '',
		shadeClose: true,
		shade: 0.8,
		area: ['60%', '70%'],
		content: '/meetingApplication/add'
	});
});
//申请会议同意
$(".showLayer").on('click','ul li .agree',function(){
	var id = $(this).closest('li').find("input[name='id']").val();
    var data = {}
    data.id = id
    data.status = 3
	$.ajax({
		url: '/meetingApplication/audit',
		data: JSON.stringify(data),
		dataType: 'json',
        method: 'post',
        contentType: 'application/json',
		success: function (e) {
			if (e.code == 0) {
				layer.msg('操作成功', {icon: 1,time: 1000}, function () {
					loadOtherData();
					var year = $(".mycal .midData .ym .y").text();
					var month = $(".mycal .midData .ym .m").text() - 1;
					var date = $(".mycal .day .nowdate").text();
					var v = moment([year, month, date]);
					draw_calander(v);
                    load_audit_status();
				})
			}
		}
	});
});
//申请会议拒绝
$(".showLayer").on('click','ul li .disagree',function(){
	var id = $(this).closest('li').find("input[name='id']").val();
	var data = {}
	data.id = id
	data.status = 3
	$.ajax({
		url: '/meetingApplication/audit',
		data: JSON.stringify(data),
		dataType: 'json',
		method: 'post',
		contentType: 'application/json',
		success: function (e) {
			if (e.code == 0) {
				layer.msg('操作成功', {icon: 1,time: 1000}, function () {
					loadOtherData();
					var year = $(".mycal .midData .ym .y").text();
					var month = $(".mycal .midData .ym .m").text() - 1;
					var date = $(".mycal .day .nowdate").text();
					var v = moment([year, month, date]);
					draw_calander(v);
                    load_audit_status();
				})
			}
		}
	});
});